package com.pds.web.testOrganizationInfo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pds.common.core.domain.entity.SysDept;
import com.pds.common.core.domain.entity.SysUser;
import com.pds.common.utils.DateUtils;
import com.pds.common.utils.SecurityUtils;
import com.pds.common.utils.StringUtils;
import com.pds.system.domain.FileUpload;
import com.pds.system.domain.SysUserRole;
import com.pds.system.mapper.*;
import com.pds.web.area.entity.Area;
import com.pds.web.area.mapper.AreaMapper;
import com.pds.web.testOrganizationInfo.domain.PdsTestOrganizationInfo;
import com.pds.web.testOrganizationInfo.domain.PdsTestOrganizationPerson;
import com.pds.web.testOrganizationInfo.mapper.PdsTestOrganizationInfoMapper;
import com.pds.web.testOrganizationInfo.mapper.PdsTestOrganizationPersonMapper;
import com.pds.web.testOrganizationInfo.service.IPdsTestOrganizationInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class PdsTestOrganizationInfoServiceImpl extends ServiceImpl<PdsTestOrganizationInfoMapper, PdsTestOrganizationInfo> implements IPdsTestOrganizationInfoService {

    @Resource
    private PdsTestOrganizationInfoMapper pdsTestOrganizationInfoMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Resource
    private PdsTestOrganizationPersonMapper pdsTestOrganizationPersonMapper;
    @Resource
    private FileUploadMapper fileUploadMapper;

    /**机构管理员角色权限字符串*/
    private static final String ORG_ADMIN_ROLE_KEY = "agencyAdmin";

    /**
     * 新增
     *
     * @param pdsTestOrganizationInfo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public Boolean addInfo(PdsTestOrganizationInfo pdsTestOrganizationInfo) {

        if (sysUserMapper.selectUserByUserName(pdsTestOrganizationInfo.getContactPhone()) != null
                || sysDeptMapper.selectDeptByDeptName(pdsTestOrganizationInfo.getCompanyName()) != null) {
            return false;
        }

        String createBy = SecurityUtils.getLoginUser().getUser().getNickName();
        Date date = DateUtils.parseDate(DateUtils.getTime());

        //1.在test_organization_info表中添加数据
        pdsTestOrganizationInfo.setMonitorCountYear("0");
        pdsTestOrganizationInfo.setTotalPerson("0人");
        pdsTestOrganizationInfo.setResearcherSeniorEngineer("0人");
        pdsTestOrganizationInfo.setSeniorEngineer("0人");
        pdsTestOrganizationInfo.setEngineer("0人");
        pdsTestOrganizationInfo.setAssistantEngineer("0人");
        pdsTestOrganizationInfo.setTechnician("0人");
        pdsTestOrganizationInfo.setOtherPerson("0人");
        pdsTestOrganizationInfo.setStatus("0");
        pdsTestOrganizationInfo.setCreateBy(createBy);
        pdsTestOrganizationInfo.setCreateTime(date);

        pdsTestOrganizationInfoMapper.insert(pdsTestOrganizationInfo);

        //2.在sys_dept表添加数据
        SysDept dept = new SysDept();

        //查询一级部门信息:0环保局，1检测机构，2企业，3运维机构
        //防止修改部门名称，导致无法添加企业机构信息
        SysDept lastDept = sysDeptMapper.getLastDeptByType(1);
        Long parentId = lastDept.getDeptId();
        String ancestors = lastDept.getAncestors();
        String[] ids = ancestors.split(",");
        if(ids.length>=3){
            //是二级以上目录
            parentId = Long.valueOf(ids[2]);
            ancestors = ids[0]+","+ids[1]+","+ids[2];
        }else{
            //是一级目录
            ancestors = ancestors+","+lastDept.getDeptId();
        }
        dept.setParentId(parentId);
        dept.setAncestors(ancestors);
        dept.setDeptName(pdsTestOrganizationInfo.getCompanyName());
        dept.setType(1);
        dept.setOrganizationId(pdsTestOrganizationInfo.getId());
        dept.setOrderNum(lastDept.getOrderNum()+1);
        dept.setLeader(pdsTestOrganizationInfo.getContactName());
        dept.setPhone(pdsTestOrganizationInfo.getContactPhone());
        dept.setCreateBy(createBy);
        dept.setCreateTime(date);

        sysDeptMapper.insertDept(dept);

        //3.在sys_user表添加数据
        SysUser user = new SysUser();

        user.setDeptId(dept.getDeptId());
        user.setUserName(pdsTestOrganizationInfo.getContactPhone());
        user.setNickName(pdsTestOrganizationInfo.getContactName());
        user.setPhonenumber(pdsTestOrganizationInfo.getContactPhone());
        user.setSex("2");
        String initPassword = sysConfigMapper.selectInitPassword();
        user.setPassword(SecurityUtils.encryptPassword(initPassword));
        user.setCreateBy(createBy);
        user.setCreateTime(date);

        sysUserMapper.insertUser(user);

        //4.将dept_id, user_id更新至company_info表
        pdsTestOrganizationInfo.setDeptId(dept.getDeptId());
        pdsTestOrganizationInfo.setUserId(user.getUserId());
        pdsTestOrganizationInfoMapper.updateById(pdsTestOrganizationInfo);

        //5.将管理员信息添加到Person表中
        Long roleId = sysRoleMapper.getRoleIdByRoleKey(ORG_ADMIN_ROLE_KEY);
        PdsTestOrganizationPerson pdsTestOrganizationPerson = new PdsTestOrganizationPerson();
        pdsTestOrganizationPerson.setUserId(user.getUserId());
        pdsTestOrganizationPerson.setDeptId(dept.getDeptId());
        pdsTestOrganizationPerson.setOrganizationId(pdsTestOrganizationInfo.getId());
        pdsTestOrganizationPerson.setPersonName(pdsTestOrganizationInfo.getContactName());
        pdsTestOrganizationPerson.setPersonCategory(String.valueOf(roleId));
        pdsTestOrganizationPerson.setPhone(pdsTestOrganizationInfo.getContactPhone());
        pdsTestOrganizationPerson.setSex("2");
        pdsTestOrganizationPerson.setStatus("0");
        pdsTestOrganizationPerson.setCreateTime(date);
        pdsTestOrganizationPerson.setRemark("无");
        pdsTestOrganizationPersonMapper.addPerson(pdsTestOrganizationPerson);

        //6.在sys_user_role表中给账号分配角色
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(user.getUserId());
        userRole.setRoleId(roleId);

        List<SysUserRole> userRoleList = new ArrayList<>();
        userRoleList.add(userRole);

        sysUserRoleMapper.batchUserRole(userRoleList);

        return true;
    }

    /**
     * 删除 -- 根据id
     *
     * @param id
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public Boolean deleteInfo(Long id) {
        return pdsTestOrganizationInfoMapper.deleteById(id) > 0;
    }

    /**
     * 更新
     *
     * @param pdsTestOrganizationInfo
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public Boolean updateInfo(PdsTestOrganizationInfo pdsTestOrganizationInfo) throws Exception {
        String updateBy = SecurityUtils.getLoginUser().getUser().getNickName();
        String phone = pdsTestOrganizationInfo.getContactPhone();
        String name = pdsTestOrganizationInfo.getContactName();
        Long userId = pdsTestOrganizationInfo.getUserId();
        Long deptId = pdsTestOrganizationInfo.getDeptId();
        pdsTestOrganizationInfo.setUpdateBy(updateBy);

        Date date = DateUtils.parseDate(DateUtils.getTime());
        pdsTestOrganizationInfo.setUpdateTime(date);

        //判断用户表是否存在同手机号
        SysUser existUser = sysUserMapper.selectUserByUserName(phone);
        if (existUser != null&& !String.valueOf(userId).equals(existUser.getUserId().toString())) {
            throw new Exception("修改失败，已存在相同手机号账户，请核实");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserName(phone);
        sysUser.setPhonenumber(phone);
        sysUser.setNickName(name);
        sysUser.setUserId(userId);
        sysUserMapper.updateUser(sysUser);

        SysDept sysDept = new SysDept();
        sysDept.setDeptId(deptId);
        sysDept.setDeptName(pdsTestOrganizationInfo.getCompanyName());
        sysDept.setLeader(name);
        sysDept.setPhone(phone);
        sysDept.setStatus(pdsTestOrganizationInfo.getStatus());
        sysDept.setUpdateBy(updateBy);
        sysDeptMapper.updateDept(sysDept);

        return pdsTestOrganizationInfoMapper.updateById(pdsTestOrganizationInfo) > 0;
    }

    /**
     * 查询 -- 分页/条件：userId，status
     *
     * @param pdsTestOrganizationInfo
     * @return
     */
    @Override
    public List<PdsTestOrganizationInfo> selectInfoList(PdsTestOrganizationInfo pdsTestOrganizationInfo) {
        List<PdsTestOrganizationInfo> infoList = pdsTestOrganizationInfoMapper.selectInfoList(pdsTestOrganizationInfo);
        //查询省市四级文字
        infoList.stream().forEach(info -> {
            StringBuilder addressCode = new StringBuilder();
            addressCode.append(info.getProvince()).append(",")
                    .append(info.getCity()).append(",")
                    .append(info.getCounty()).append(",")
                    .append(info.getTownship());
            String addressText = areaMapper.selectAddressByCode(addressCode.toString());
            info.setAddressText(addressText);
        });

        infoList.stream().forEach(info -> {
            getFileInfo(info);
        });

        return infoList;
    }

    /**
     * 保存机构检测范围
     *
     * @param map - organizationId 机构id
     *            - categoryIds 检测范围科目id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addOrganizationCategory(Map map) {
        String organizationId = String.valueOf(map.get("organizationId"));
        String categoryIds = String.valueOf(map.get("categoryIds"));
        //先删除
        pdsTestOrganizationInfoMapper.deleteOrganizationCategoryById(organizationId);
        //再保存
        if(!ObjectUtils.isEmpty(map.get("categoryIds"))) {
            pdsTestOrganizationInfoMapper.addOrganizationCategory(organizationId, categoryIds);
        }
    }

    /**
     * 查询机构检测范围
     * organizationId 机构id
     *
     * @param organizationId
     * @return
     */
    @Override
    public List<String> getOrganizationCategory(String organizationId) {
        return pdsTestOrganizationInfoMapper.getOrganizationCategory(organizationId);
    }

    /**
     * 启用、禁用机构
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Long id, String status) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(!"0,1".contains(status)){
            throw new RuntimeException("参数错误！");
        }
        PdsTestOrganizationInfo info = new PdsTestOrganizationInfo();
        info.setId(id);
        info.setStatus(status);
        info.setUpdateTime(new Date());
        info.setUpdateBy(user.getNickName());
        pdsTestOrganizationInfoMapper.updateById(info);
        //更新部门表
        SysDept sysDept = new SysDept();
        sysDept.setOrganizationId(id);
        sysDept.setStatus(status);
        sysDept.setUpdateBy(user.getNickName());
        sysDept.setType(1);
        sysDeptMapper.updateDeptByOrganizationId(sysDept);
    }

    /**
     * 批量导入检测机构
     *
     * @param list
     */
    @Override
    public void batchInsert(List<PdsTestOrganizationInfo> list) throws Exception {
        int row = 1;
        for (PdsTestOrganizationInfo info : list) {
            try {
                //省市县转换为code
                Area province = areaMapper.selectAddressByName(info.getProvince(),null);
                if(province==null){
                    throw new Exception("第"+row+"行错误：省选择错误");
                }
                Area city = areaMapper.selectAddressByName(info.getCity(),province.getCode());
                if(city == null){
                    throw new Exception("第"+row+"行错误：市选择错误");
                }
                Area county = areaMapper.selectAddressByName(info.getCounty(),city.getCode());
                if(county==null){
                    throw new Exception("第"+row+"行错误：县区选择错误");
                }
                Area township = areaMapper.selectAddressByName(info.getTownship(),county.getCode());
                if(township==null) {
                    throw new Exception("第"+row+"行错误：乡镇/街道选择错误");
                }
                info.setProvince(province.getCode());
                info.setCity(city.getCode());
                info.setCounty(county.getCode());
                info.setTownship(township.getCode());
                addInfo(info);
            } catch (Exception e) {
                throw new Exception("第"+row+"行错误："+e.getMessage());
            }
            row++;
        }
    }

    private void getFileInfo(PdsTestOrganizationInfo info){
        String fileIds = "";
        if (StringUtils.isNotEmpty(info.getCertificateAttachments())){
            fileIds += info.getCertificateAttachments() + ",";
        }
        if (StringUtils.isNotEmpty(info.getRangeAttachments())){
            fileIds += info.getRangeAttachments() + ",";
        }
        if(StringUtils.isNotEmpty(fileIds)){
            fileIds = fileIds.substring(0,fileIds.length()-1);
            List<FileUpload> fileUploads = fileUploadMapper.selectFileUploadListByIds(fileIds.split(","));
            for (int i = 0; i < fileUploads.size(); i++){
                FileUpload fileUpload = fileUploads.get(i);
                if(fileUpload.getAttachmentId().equals(info.getCertificateAttachments())){
                    info.setCertificateFile(fileUpload.getFileName());
                    info.setCertificateUrl(fileUpload.getUrl());
                }else if(fileUpload.getAttachmentId().equals(info.getRangeAttachments())){
                    info.setRangeFile(fileUpload.getFileName());
                    info.setRangeUrl(fileUpload.getUrl());
                }
            }
        }
    }
}
